package com.juli.school.service.impl;

import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.juli.school.dao.mapper.DDLMapper;
import com.juli.school.utils.core.model.CommonResp;

@Service
public class DDLService {
	
	private static final Logger logger = LoggerFactory.getLogger(DDLService.class);
	
	@Resource
	DDLMapper ddlMapper;
	
	@Value("${database.schema}")
	private String schema;
	
	/**
	 * @Description: 操作表，统一改
	 * @author gaoxiang
	 * @date 2017年8月31日 下午11:27:17
	 */
	public CommonResp<String> alterTable(String type,String sql) {
		CommonResp<String> commonResp = new CommonResp<String>();
		try {
			if ("all".equals(type)) {
				int i = 0;
				List<String> tables = ddlMapper.queryTables(schema);
				for (String tableName : tables) {
					try {
						ddlMapper.excuteSql(String.format(sql, tableName));
						i++;
					} catch (Exception e) {
						logger.info("执行sql失败,表名【{}】,原因:{}", tableName, e.getCause());
					}
				}
				commonResp.setData(String.format("共调整了【%s】张表,sql->%s", i, sql));
			} else {
				ddlMapper.excuteSql(sql);
				commonResp.setData(String.format("共调整了【1】张表,sql->%s", sql));
			}
			commonResp.success();
		} catch (Exception e) {
			commonResp.exception("sql执行失败,原因:" + e.getCause());
			logger.error("sql执行失败,原因:",e);
		}
		return commonResp;
	}
}
